package com.lagou.server;

import com.lagou.handler.RegistryHandler;
import com.lagou.handler.UserServerHandler;
import com.lagou.rpc.JSONSerializer;
import com.lagou.rpc.RpcDecoder;
import com.lagou.rpc.RpcRequest;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ServerBootstrap implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private UserServerHandler userServerHandler;

    @Autowired
    private RegistryHandler registryHandler;

    @Value("${rpc.server.host}")
    private String rpcServerHost;

    @Value("${rpc.server.port}")
    private Integer rpcServerPort;

    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        try {
            startServer(rpcServerHost, rpcServerPort);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void startServer(String hostName, int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        io.netty.bootstrap.ServerBootstrap serverBootstrap = new io.netty.bootstrap.ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {

                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
//                        pipeline.addLast(new StringDecoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(userServerHandler);
                    }
                });

        serverBootstrap.bind(hostName, port).sync();

        registryHandler.registToZK();
    }

}
